;
(function (window, document, $) {
    window.tableMenuUtil = {
        init: function (menuId, data, cb) {
            $('.layui-table-body tr').each(function (e) {
                //表单鼠标右键操作
                $(this).mousedown(function (e) {
                    var index = $(this).attr('data-index');  //获取该表格行的数据
                    if (e.which === 3) {    //判断时鼠标右键按下
                        //显示鼠标右键菜单列表
                        var x = e.originalEvent.x + 'px';  //获取鼠标位置x坐标
                        var y = e.originalEvent.y + 'px';  //获取鼠标位置y坐标
                        $("#" + menuId).css({
                            top: y,    //定位右键菜单的位置
                            left: x
                        });
                        $("#" + menuId).show();
                        cb(data[index]);
                    }
                    if (e.which == 1) {
                        $("#" + menuId).hide();    //如果是点击的鼠标左键，则隐藏菜单
                    }
                });
            });
        }
    },
        window.layerUtil = {
            loading: function (type) {
                if (type == undefined) {
                    return window.top.layer.open({
                        type: 3,
                        shade: 0.7
                    });
                } else {
                    return window.top.layer.load(1, {
                        shade: [0.8, '#fff']
                    });
                }
            },
            closeLayer: function (index) {
                index = index || window.top.layer.getFrameIndex(window.name);
                window.top.layer.close(index);
            },
            confirm: function (msg, yesCb, cancelCb) {
                window.top.layer.confirm(msg, {icon: 3, title: '提示'}, function (index) {
                    layerUtil.closeLayer(index);
                    if (yesCb !== undefined) {
                        yesCb();
                    }
                }, function (index) {
                    layerUtil.closeLayer(index);
                    if (cancelCb !== undefined) {
                        cancelCb();
                    }
                });
            },
            msg: function (obj, cb) {
                window.top.layer.msg(obj.msg, {
                    icon: obj.icon || -1,
                    time: obj.time || 1000
                }, function () {
                    if (cb != undefined) {
                        cb();
                    }
                });
            },
            success: function (msg, cb) {
                layerUtil.msg({
                    icon: 1,
                    msg: msg,
                    time: 1000
                }, function () {
                    if (cb != undefined) {
                        cb();
                    }
                });
            },
            error: function (msg, cb) {
                layerUtil.msg({
                    icon: 5,
                    msg: msg || "加载数据失败，请稍后再试",
                    time: 1000
                }, function () {
                    if (cb != undefined) {
                        cb();
                    }
                });
            },
            iframe: function (obj) {
                var iframe = {
                    type: 2,
                    title: obj.title || "标题",
                    area: obj.area || ['1080px', '600px'],
                    fixed: false, //不固定
                    maxmin: obj.maxmin || false,
                    content: obj.content,
                    cancel: function (index, layero) {
                        if (obj.cancel !== undefined) {
                            obj.cancel();
                            return true;
                        } else {
                            return true;
                        }
                    }
                };
                if (obj.buttons != null && obj.buttons.length > 0) {
                    var buttons = [];
                    for (var i = 0; i < obj.buttons.length; i++) {
                        buttons.push(obj.buttons[i].name);
                        if (i === 1) {
                            iframe.btn2 = function (index, layero) {
                                obj.buttons[1].afterClick(index, layero);
                            }
                        } else if (i === 2) {
                            iframe.btn3 = function (index, layero) {
                                obj.buttons[2].afterClick(index, layero);
                            }
                        }
                    }
                    iframe.btn = buttons;
                    iframe.yes = function (index, layero) {
                        obj.buttons[0].afterClick(index, layero);
                    }
                }
                return window.top.layer.open(iframe);
            }
        },
        window.dateUtil = {
            getNowDateTimeStr: function () {
                var date = new Date();
                this.year = date.getFullYear();
                this.month = date.getMonth() + 1;
                this.date = date.getDate();
                this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
                this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
                this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                return this.year + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second;
            },
            getNowDateStr: function () {
                var date = new Date();
                this.year = date.getFullYear();
                this.month = date.getMonth() + 1;
                this.date = date.getDate();
                return this.year + "-" + this.month + "-" + this.date;
            }
        },
        window.ajaxUtil = {
            post: function (data, url, successCb, errorCb) {
                $.ajax({
                    type: "POST",
                    url: ServerURL + url,
                    data: JSON.stringify((data || {})),
                    beforeSend: function (request) {
                        request.setRequestHeader("rf-auth", tokenUtil.getToken());
                    },
                    dataType: "json",
                    contentType: "application/json",
                    success: function (res) {
                        successCb(res);
                    },
                    error: function (error) {
                        ajaxUtil.handleError(error, errorCb);
                    }
                });
            },
            simplePost: function (data, url, successCb, loadingFlag, tipsFlag) {
                let loadingIndex;
                if (loadingFlag !== 0) {
                    loadingIndex = layerUtil.loading(1);
                }
                let tipMsg = "操作";
                let operUrl = url.substring(url.lastIndexOf("/") + 1);
                if (operUrl.startsWith("insert")) {
                    tipMsg = "新增";
                } else if (operUrl.startsWith("update")) {
                    tipMsg = "更新";
                } else if (operUrl.startsWith("delete")) {
                    tipMsg = "删除";
                } else if (operUrl.startsWith("truncate")) {
                    tipMsg = "清空";
                } else if (operUrl.startsWith("import")) {
                    tipMsg = "导入";
                } else if (operUrl.startsWith("export")) {
                    tipMsg = "导出";
                }
                this.post(data, url, function (res) {
                    if (loadingIndex) {
                        layerUtil.closeLayer(loadingIndex);
                    }
                    if (res.code === 200) {
                        if (tipsFlag !== 0) {
                            layerUtil.success(tipMsg + "成功");
                        }
                        successCb(res.data);
                    } else {
                        layerUtil.error(res.msg);
                    }
                }, function () {
                    if (loadingIndex) {
                        layerUtil.closeLayer(loadingIndex);
                    }
                });
            },
            get: function (url, successCb, errorCb) {
                $.ajax({
                    type: 'Get',
                    url: ServerURL + url,
                    beforeSend: function (request) {
                        request.setRequestHeader("rf-auth", tokenUtil.getToken());
                    },
                    dataType: "json",
                    contentType: "application/json",
                    success: function (res) {
                        successCb(res);
                    },
                    error: function (error) {
                        ajaxUtil.handleError(error, errorCb);
                    }
                });
            },
            simpleGet: function (url, successCb, errorCb) {
                this.get(url, function (res) {
                    if (res.code === 200) {
                        successCb(res.data);
                    } else {
                        layerUtil.error(res.msg);
                    }
                }, errorCb);
            },
            handleError: function (error, errorCb) {
                let status = error.status;
                if (status === 400 || status === 403 || status === 405 || status === 415 || status === 500) {
                    layerUtil.error(error.responseJSON.msg, function () {
                        let code = error.responseJSON.code;
                        // Token相关异常 返回登录页
                        if (code === 10013 || code === 10014 || code === 10015 || code === 10018) {
                            window.top.location.href = "login.html";
                        }
                    });
                } else {
                    layerUtil.error("服务器忙，请稍后再试");
                }
                if (errorCb !== undefined) {
                    errorCb(error);
                }
            },
            loadDict: function (dictTypes, cb) {
                this.get("/dict/queryDictData?dictTypes=" + dictTypes, function (res) {
                    if (res.code === 200) {
                        cb(res.data);
                    } else {
                        layerUtil.error(res.msg);
                    }
                });
            }
        },
        window.ServerURL = "http://localhost:8888/rabbit-admin",
        window.tokenUtil = {
            getToken: function () {
                return window.sessionStorage.getItem("token")
            },
            setToken: function (token) {
                window.sessionStorage.setItem("token", token)
            },
            getAuthHeader: function () {
                return {
                    "rf-auth": this.getToken()
                }
            }
        },
        window.doNothing = function () {
            // 屏蔽浏览器右键菜单
            window.event.returnValue = false;
            return false;
        },
        window.isEmpty = function (obj) {
            if (typeof obj == "undefined" || obj == null || obj == "") {
                return true;
            } else {
                return false;
            }
        },
        window.reloadParentTable = function (tableName) {
            if (parent.window.length <= 1) {
                parent.window[0].reloadTable();
            } else {
                for (let i = 0; i < parent.window.length; i++) {
                    if (parent.window[i].document.getElementById(tableName) != null) {
                        parent.window[i].reloadTable();
                        break;
                    }
                }
            }
        },
        window.execParentFunction = function (uniqueElementId, functionName) {
            for (let i = 0; i < parent.window.length; i++) {
                if (parent.window[i].document.getElementById(uniqueElementId) != null) {
                    parent.window[i].eval(functionName);
                    break;
                }
            }
        },
        // 缓存临时数据
        window.putTempData = function (key, value) {
            if (value) {
                layui.sessionData('tempData', {key: key, value: value});
            } else {
                layui.sessionData('tempData', {key: key, remove: true});
            }
        },
        // 获取缓存临时数据
        window.getTempData = function (key) {
            return layui.sessionData('tempData')[key];
        },
        window.commonUtil = {
            getUUID: function () {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";

                var uuid = s.join("");
                return uuid;
            },
            noToChinese: function (num) {
                if (!/^\d*(\.\d*)?$/.test(num)) {
                    return "Number is wrong!";
                }
                var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
                var BB = new Array("", "十", "百", "千", "万", "亿", "点", "");
                var a = ("" + num).replace(/(^0*)/g, "").split("."),
                    k = 0,
                    re = "";
                for (var i = a[0].length - 1; i >= 0; i--) {
                    switch (k) {
                        case 0:
                            re = BB[7] + re;
                            break;
                        case 4:
                            if (!new RegExp("0{4}\\d{" + (a[0].length - i - 1) + "}$").test(a[0]))
                                re = BB[4] + re;
                            break;
                        case 8:
                            re = BB[5] + re;
                            BB[7] = BB[5];
                            k = 0;
                            break;
                    }
                    if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re;
                    if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re;
                    k++;
                }
                if (a.length > 1) //加上小数部分(如果有小数部分)
                {
                    re += BB[6];
                    for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)];
                }
                return re;
            },
            getRequestParameter: function () {
                const url = window.location.search; //获取url中"?"符后的字串
                const theRequest = {};
                if (url.indexOf("?") !== -1) {
                    const str = url.substr(1);
                    const strs = str.split("&");
                    for (let i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            }
        }
})(window, document, $);